package com.app.twth.base;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.app.twth.bean.LoadingBean;

import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;

public class BaseAndroidViewModel<BM extends BaseModel> extends AndroidViewModel {
    protected BM mModel;

    public MutableLiveData<LoadingBean> isLoading = new MutableLiveData<LoadingBean>();
    public MutableLiveData<String> errorResultCode = new MutableLiveData<>();//错误提示
    public MutableLiveData<String> infoResultCode = new MutableLiveData<>();//错误特殊提示
    public String infoResultMsg;

    public BaseAndroidViewModel(@NonNull Application application) {
        super(application);
        try {
            mModel = createInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public BM createInstance() throws Exception {

        // 获取subclass的参数化类型，这里的subclass应该是GenericReflectionExample的子类
        ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
        Class<BM> clazz = (Class<BM>) (parameterizedType).getActualTypeArguments()[0];
        // 通过反射获取无参构造器
        Constructor<BM> constructor = clazz.getConstructor();
        // 创建实例
        BM instance = constructor.newInstance();
        return instance;
    }

    /**
     * 解除model中所有订阅者
     */
    public void dispose() {
        if (mModel != null) {
            mModel.dispose();
            mModel = null;
        }
    }
}
